package com.lz.service.excel.config;


import io.swagger.annotations.ApiModelProperty;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class ExcelDemo {
    /**
     * @param list
     * @param response
     * @ApiModelProperty(value = "车牌号", required = true)
     * 这个表会根据字段的注解决定是否参与展示 required 为true则展示
     * 展示名称为value的值
     */
    //在此调整逻辑
//
    private static boolean isaBoolean(ApiModelProperty apiModelProperty) {
        return apiModelProperty != null && !apiModelProperty.required();
    }

    /**
     * 将 Excel 文件写入响应流
     *
     * @param 要写入的     Excel 文件
     * @param response HttpServletResponse 对象
     * @throws IOException 当写入响应流出错时抛出
     */

    // ... 已有代码 ...

    /**
     * 生成 Excel 文件
     *
     * @param list 数据列表
     * @return 生成的 Excel 文件
     * @throws IllegalArgumentException 当列表为空或 null 时抛出
     * @throws IOException              当文件操作出错时抛出
     */
    public static File generateExcelFile(List<?> list)  {
        if (list == null || list.isEmpty()) {
            throw new IllegalArgumentException("List cannot be null or empty");
        }

        // 获取实体类的Class对象
        Class<?> clazz = list.get(0).getClass();

        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        Sheet sheet = workbook.createSheet(clazz.getSimpleName());

        // 获取所有字段
        Field[] fields = clazz.getDeclaredFields();
        Row headerRow = sheet.createRow(0);

        // 用于存储需要导出的字段索引
        int columnIndex = 0;
        for (Field field : fields) {
            ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
            if (isaBoolean(apiModelProperty)) {
                Cell cell = headerRow.createCell(columnIndex);
                cell.setCellValue(apiModelProperty.value());
                field.setAccessible(true); // 确保可以访问私有字段
                columnIndex++;
            }
        }

        // 填充数据
        int rowNum = 1;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Object obj : list) {
            Row row = sheet.createRow(rowNum++);
            int cellIndex = 0;
            for (Field field : fields) {
                ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
                if (isaBoolean(apiModelProperty)) {
                    try {
                        Object value = field.get(obj);
                        Cell cell = row.createCell(cellIndex);
                        if (value instanceof Date) {
                            cell.setCellValue(dateFormat.format((Date) value));
                        } else if (value != null) {
                            cell.setCellValue(value.toString());
                        }
                    } catch (IllegalAccessException e) {
                        // 这里可以使用日志记录，例如使用 SLF4J
                        e.printStackTrace();
                    }
                    cellIndex++;
                }
            }
        }

        // 自动调整列宽
        for (int i = 0; i < columnIndex; i++) {
            sheet.autoSizeColumn(i);
        }

        // 创建临时文件
        File tempFile = null;
        try {
            tempFile = File.createTempFile("excel-export", ".xlsx");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            workbook.write(fos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return tempFile;
    }

    /**
     * 将 Excel 文件写入响应流，通过 RequestContextHolder 获取 HttpServletResponse 对象
     *
     * @param file 要写入的 Excel 文件
     * @throws IOException           当写入响应流出错时抛出
     * @throws IllegalStateException 当无法获取 HttpServletResponse 对象时抛出
     */
    public static void writeExcelToResponse(File file) throws IOException {
        if (file == null || !file.exists()) {
            throw new IllegalArgumentException("File cannot be null or not exist");
        }

        // 通过 RequestContextHolder 获取 HttpServletResponse 对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new IllegalStateException("Cannot get ServletRequestAttributes from RequestContextHolder");
        }
        HttpServletResponse response = attributes.getResponse();
        if (response == null) {
            throw new IllegalStateException("Cannot get HttpServletResponse from ServletRequestAttributes");
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=file.xlsx");

        // 写入响应流
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        }
    }



}
